import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import { wrapperEnv } from './build/utils';

import { viteMockServe } from 'vite-plugin-mock';

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env);
  const { VITE_USE_MOCK } = viteEnv;
  return {
    plugins: [
      vue(),
      AutoImport({
        imports: ['vue', 'vue-router'], // 需要自动引入api的库
        dts: resolve(__dirname, 'src/auto-import.d.ts'), //可以选择auto-import.d.ts生成的位置，使用ts建议设置为'src/auto-import.d.ts' ,注意:这里配置之后会在启动之后多次编译，具体原因无法找到，可以选择注释掉，不影响使用
      }),
      viteMockServe({
        supportTs: false,
        mockPath: './src/mock',
        logger: true,
        localEnabled: VITE_USE_MOCK, // 开发打包开关
        prodEnabled: VITE_USE_MOCK, // 生产打包开关
        watchFiles: true,
        injectCode: `
            import { setupProdMockServer } from './src/mock/mockProdServer';
            setupProdMockServer();
          `,
      }),
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "@/styles/index.less";',
          javascriptEnabled: true,
        },
      },
    },
    server: {
      host: true,
      open: 'chrome',
    },
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: import.meta?.VITE_DROP_CONSOLE || false,
        },
      },
      // Turning off brotliSize display can slightly reduce packaging time
      brotliSize: false,
      chunkSizeWarningLimit: 2000,
    },
  };
});
